/*
Copyright 2009 Lawren Quigley-Jones

   stage-assistant.js is part of Preopoly.

   Preopoly is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Preopoly is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Preopoly.  If not, see <http://www.gnu.org/licenses/>.

   Contact Lawren Quigley-Jones with questions or bugs:
   lawrenqj@gmail.com
*/

function StageAssistant() {
}


StageAssistant.prototype.setup = function() {
try {
  debug = false;

  disableCards = 0;
  alwaysRoll = false;
  //alwaysRoll = 3;

  loadPrefsCookie();
  if ( ! prefs ) clearPrefs();
  if ( ! prefs.housePriceMultiplier ) {
    clearPrefs();
    savePrefsCookie();
  }

  if ( prefs.bankMode == 'true' ) {
    prefs.displayPropertyCards = 'false';
    //prefs.disableEndTurn = 'true';
  }

  chanceExceptions = "";	// this is for chance cards that change behavior

  killGame = false;

  setPropertyGlobal();
  loadPropertyCookie();

  this.setChanceGlobal();
  this.setCommunityChestGlobal();

  this.loadDynamicObjects();

  this.controller.pushScene('welcome');
  //this.controller.pushScene('board');
  //this.controller.pushScene('props');
  //this.controller.pushScene('trade');
  //this.controller.pushScene('preferences');
} catch(x) { if ( debug ) Mojo.Log.error('Exception in stage setup: ' + x); }
}

StageAssistant.prototype.screenOrientationChanged = function() {
  debugMessage("screen orientation");
}

clearPrefs = function() {
  prefs = {
    version: '10',
    numPlayers: 3,
    startMoney: 1500,
    disableEndTurn: 'false',
    doubleOnGo: 'false',
    rentInJail: 'false',
    payToFreeParking: 'false',
    computerOffersTrades: 5,
    showSteps: 'true',
    removeBankruptPieces: 'true',
    displayPropertyCards: 'true',

    houseBuyBackRate: .5,
    housePriceMultiplier: 50,
    mortgageRate: .1,
    mortgageValue: .5,

    bankMode: 'false',

    complexDebts: 'false',
    moneyDown: .20,
    minimumPayments: .05,
    interestRate: .05,
    //maxDebt: 1000
  };
}

clearDiceCookie = function() {
  var savedRollCookie = new Mojo.Model.Cookie("savedRoll");
  savedRollCookie.remove();
}

clearDynamicObjects = function() {
try {
  if ( prefs.startMoney == undefined ) prefs.startMoney = 1500;

		// clear dice cookie
  clearDiceCookie();

  clearPropertyOwnerArray();
  resetPlayerArray();

  pickPlayers();

  curPlayer = playerList[0];
  curPlayerCookie = new Mojo.Model.Cookie("curPlayerCookie");
  curPlayerCookie.put(curPlayer);

		// clear free parking cookie value
  freeParkingMoney = 0;
  freeParkingMoneyCookie = new Mojo.Model.Cookie("freeParkingMoneyCookie");

		// clear ban monie cookie value
  bankMoney = 0;
  bankMoneyCookie = new Mojo.Model.Cookie("bankMoneyCookie");
  bankMoneyCookie.put(bankMoney);

  killGame = true;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in clear dynamic objects: ' + x); }
}

clearProperty = function(i) {
  propertyOwner[i] = { owner: null, ownedHouses: 0, propertyMortgaged: 0, debt: 0 };
}

clearPropertyOwnerArray = function() {
		// clear property owener cookie
  propertyOwner = [];
  for ( var i=0; i<=39; i++ )
    clearProperty(i);
}

inArray = function(v, a) {
  for ( var i=0; i<=a.length; i++ ) {
    if ( a[i] == v )
      return 1;
  }
  return 0;
}

clearSinglePlayer = function(i) {
      playerArray[i].position = 0;
      playerArray[i].money = prefs.startMoney;
      playerArray[i].jailstate = 0;
      playerArray[i].jailturns = 0;
      playerArray[i].jailcards = 0;
      playerArray[i].stillowe = 0;
      playerArray[i].stilloweto = null;
      playerArray[i].bankrupt = 0;
      playerArray[i].doubleRolls = 0;
      playerArray[i].debt = 0;
}

resetPlayerArray = function() {
		// clear player array cookie
  playerNamesCookie = new Mojo.Model.Cookie("playerNamesCookie");
  playerArray = playerNamesCookie.get();
  if ( playerArray == undefined ) {
    resetPlayerNames();
    playerNamesCookie.put(playerArray);
  }
  else {
    for ( var i=0; i<playerArray.length; i++ ) {
      clearSinglePlayer(i);
    }
    this.playerNamesCookie.put(playerArray);
  }
}

resetPlayerNames = function() {
  playerArray = [];
  playerArray[0] = { playerName: 'Dog', playerType: 'human', position: 0, icon: '<img style="width:25px;"src="images/dog.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[1] = { playerName: 'Hat', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/hat.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[2] = { playerName: 'Boat', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/boat.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[3] = { playerName: 'Thimble', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/thimble.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[4] = { playerName: 'Cannon', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/cannon.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[5] = { playerName: 'Car', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/car.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[6] = { playerName: 'Shoe', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/shoe.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[7] = { playerName: 'Iron', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/iron.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
  playerArray[8] = { playerName: 'Wheelbarrow', playerType: 'computer', position: 0, icon: '<img style="width:25px;"src="images/wheelbarrow.png">', money: prefs.startMoney, jailstate: 0, jailturns: 0, stillowe: 0, stilloweto: null, bankrupt: 0, doubleRolls: 0, debt: 0 };
}

pickPlayers = function() {
try {
  if ( playerArray == undefined ) {
    resetPlayerArray();
    if ( debug) Mojo.Log.error("pickPlayers was called before resetPlayerArray");
  }

  playerListCookie = new Mojo.Model.Cookie("playerListCookie");
		//first we are going to shuffle all the pieces so we are dealing with a random set.
  var allPieces = shuffleCards(playerArray.length);
  playerList = [];
		//now go through each piece and pick out the human players.
  for ( var i=0; i<allPieces.length; i++ ) {
    if ( ! isComputer(allPieces[i]) ) playerList.push(allPieces[i]);

    if ( playerList.length >= prefs.numPlayers ) {
      playerListCookie.put(playerList);
      //debugMessage("player list: " + playerList.join(" "));
      return 0;
    }
  }
		// if we get here then we need to fill in the player list with computer players.
  for ( var i=0; i<playerArray.length; i++ ) {
    if ( isComputer(allPieces[i]) ) playerList.push(allPieces[i]);

    if ( playerList.length >= prefs.numPlayers ) {
		// we need to shuffle this because computers will always be last
      playerListCookie.put(shuffle(playerList));
      //debugMessage("player list: " + playerList.join(" "));
      return 0;
    }
  }

  if ( debug ) Mojo.Log.error("failed to populate player list... " + playerList.join(" "));
} catch(x) { if ( debug ) Mojo.Log.error('Exception in pick players: ' + x); }
}

StageAssistant.prototype.loadDynamicObjects = function() {
try {
		// property Owner array
  propertyCookie = new Mojo.Model.Cookie("propertyCookie");
  propertyOwner = propertyCookie.get();
  if ( ! propertyOwner )
    clearPropertyOwnerArray();

		// player array
  playerCookie = new Mojo.Model.Cookie("playerCookie");
  playerArray = playerCookie.get();
  if ( playerArray == undefined )
    resetPlayerArray();

		// player list
  playerListCookie = new Mojo.Model.Cookie("playerListCookie");
  playerList = playerListCookie.get();
  if ( playerList == undefined ) pickPlayers();
  //debugMessage("got player list from cookie: " + playerList.join(" "));

		// curPlayer
  curPlayerCookie = new Mojo.Model.Cookie("curPlayerCookie");
  curPlayer = curPlayerCookie.get();
  if ( curPlayer == undefined )
    curPlayer = playerList[0];

		// free parking money
  freeParkingMoneyCookie = new Mojo.Model.Cookie("freeParkingMoneyCookie");
  freeParkingMoney = freeParkingMoneyCookie.get();
  if ( freeParkingMoney == undefined )
    freeParkingMoney = 0;

		// bank money
  bankMoneyCookie = new Mojo.Model.Cookie("bankMoneyCookie");
  bankMoney = bankMoneyCookie.get();
  if ( bankMoney == undefined )
    bankMoney = 0;

  saveDynamicObjects();
} catch(x) { if ( debug ) Mojo.Log.error('Exception in load dynamic objects: ' + x); }
}

saveDynamicObjects = function() {
  propertyCookie = new Mojo.Model.Cookie("propertyCookie");
  propertyCookie.put(propertyOwner);

  playerCookie = new Mojo.Model.Cookie("playerCookie");
  playerCookie.put(playerArray);

  curPlayerCookie = new Mojo.Model.Cookie("curPlayerCookie");
  curPlayerCookie.put(curPlayer);

  freeParkingMoneyCookie = new Mojo.Model.Cookie("freeParkingMoneyCookie");
  freeParkingMoneyCookie.put(freeParkingMoney);

  bankMoneyCookie = new Mojo.Model.Cookie("bankMoneyCookie");
  bankMoneyCookie.put(bankMoney);
}

loadPropertyCookie = function() {
try {
  var tmparray = [];
  var propertyArrayCookie = new Mojo.Model.Cookie("propertyArrayCookie");

		// take care of my property Array Cookie Hack
  var oldpropertyArrayCookie = new Mojo.Model.Cookie("propertyArrayCookie" + 39);
  var tmparray2 = oldpropertyArrayCookie.get();
  if ( tmparray2 != undefined ) {
    for ( var i=0; i <= 39; i++ ) {
      oldpropertyArrayCookie = new Mojo.Model.Cookie("propertyArrayCookie"+i);
      tmparray2 = oldpropertyArrayCookie.get();
      if ( tmparray2 != undefined ) {
        tmparray[i] = tmparray2[propertyName];
        oldpropertyArrayCookie.remove();
      }
    }
    if ( debug) Mojo.Log.error("importing the old style cookies: " + tmparray);
    propertyArrayCookie.put(tmparray);
  }

		// this is the standard cookie load
  tmparray = propertyArrayCookie.get();
  if ( tmparray ) {
    for ( var i=0; i <= 39; i++ )
      propertyArray[i][propertyName] = tmparray[i];
  }
  //else {
  //  for ( var i=0; i <= 39; i++ )
  //    tmparray[i] = propertyArray[i][propertyName];
  //  propertyArrayCookie.put(tmparray);
  //}

  for ( var i=0; i <= 39; i++ )
    if ( propertyArray[i][housePrice] > 4 )
      setPropertyGlobal();

} catch(x) { if ( debug ) Mojo.Log.error('Exception in creating property cookie: ' + x); }
}

setPropertyGlobal = function() {
try {
        propertyArray = [];
	house = [];
	propertyName = 0;
	propertyColor = 1;
	ticposition = 2;
	propertylocation = 3;
	price = 4;
	house[0] = 5;
	house[1] = 6;
	house[2] = 7;
	house[3] = 8;
	house[4] = 9;
	house[5] = 10; // hotel
	housePrice = 11; //( divided by housePriceMultiplier)

        propertyArray[0] = ['Payday','white',
		'',
		'left:270px;top:270px;height:25px;width:24px;',
		0,,,,,,, ];
        propertyArray[1] = ['Old Colony ave.','#550033',
		'left:100px;top:15px;',
		'left:240px;top:274px;height:25px;width:24px;',
		60,2,10,30,90,160,250,1 ];
        propertyArray[2] = ['Social Circle','white',
		'',
		'left:215px;top:274px;height:25px;width:24px;',
		0,,,,,,, ];
        propertyArray[3] = ['Columbia rd.','#550033',
		'left:100px;top:10px;',
		'left:189px;top:274px;height:25px;width:24px;',
		60,4,20,60,180,320,450,1 ];
        propertyArray[4] = ['Taxes','white',
		'',
		'left:164px;top:274px;height:25px;width:24px;',
		0,,,,,,, ];
        propertyArray[5] = ['Redline','white',
		'left:60px;top:15px;border-style:solid;border-width:1px;',
		'left:138px;top:265px;height:34px;width:25px;',
		200,,,,,,, ];
        propertyArray[6] = ['Huntington ave.','#6C8CAF',
		'left:120px;top:15px;',
		'left:113px;top:274px;height:25px;width:24px;',
		100,6,30,90,270,400,550,1 ];
        propertyArray[7] = ['Luck of the Draw','white',
		'',
		'left:87px;top:274px;height:25px;width:24px;',
		0,,,,,,, ];
        propertyArray[8] = ['Tremont st.','#6C8CAF',
		'left:120px;top:10px;',
		'left:61px;top:274px;height:25px;width:24px;',
		100,6,30,90,270,400,550,1 ];
        propertyArray[9] = ['Columbus ave.','#6C8CAF',
		'left:120px;top:5px;',
		'left:36px;top:274px;height:25px;width:24px;',
		120,8,40,100,300,450,600,1 ];
        propertyArray[10] = ['Prison','white',
		'',
		'left:5px;top:270px;height:25px;width:24px;',
		0,,,,,,, ];
        propertyArray[11] = ['Parsons st.','maroon',
		'left:140px;top:15px;',
		'left:1px;top:240px;height:24px;width:25px;',
		140,10,50,150,450,625,750,2 ];
        propertyArray[12] = ['Cable Company','white',
		'left:80px;top:15px;border-style:solid;border-width:1px;',
		'left:1px;top:214px;height:25px;width:34px;',
		150,,,,,,, ];
        propertyArray[13] = ['Warren st.','maroon',
		'left:140px;top:10px;',
		'left:1px;top:189px;height:24px;width:25px;',
		140,10,50,150,450,625,750,2 ];
        propertyArray[14] = ['Market st.','maroon',
		'left:140px;top:5px;',
		'left:1px;top:164px;height:24px;width:25px;',
		160,12,60,180,500,700,900,2 ];
        propertyArray[15] = ['Greenline','white',
		'left:60px;top:10px;border-style:solid;border-width:1px;',
		'left:1px;top:138px;height:24px;width:34px;',
		200,,,,,,, ];
        propertyArray[16] = ['Holland st.','orange',
		'left:160px;top:15px;',
		'left:1px;top:113px;height:24px;width:25px;',
		180,14,70,200,550,750,950,2 ];
        propertyArray[17] = ['Social Circle','white',
		'',
		'left:1px;top:87px;height:24px;width:25px;',
		0,,,,,,, ];
        propertyArray[18] = ['Highland ave.','orange',
		'left:160px;top:10px;',
		'left:1px;top:61px;height:24px;width:25px;',
		180,14,70,200,550,750,950,2 ];
        propertyArray[19] = ['Elm st.','orange',
		'left:160px;top:5px;',
		'left:1px;top:36px;height:24px;width:25px;',
		200,16,80,220,600,800,1000,2 ];
        propertyArray[20] = ['Day Off','white',
		'',
		'left:5px;top:6px;height:24px;width:25px;',
		0,,,,,,, ];
        propertyArray[21] = ['Prospect st.','red',
		'left:180px;top:15px;',
		'left:36px;top:1px;height:25px;width:24px;',
		220,18,90,250,700,875,1050,3 ];
        propertyArray[22] = ['Luck of the Draw','white',
		'',
		'left:62px;top:1px;height:25px;width:24px;',
		0,,,,,,, ];
        propertyArray[23] = ['Broadway','red',
		'left:180px;top:10px;',
		'left:87px;top:1px;height:25px;width:24px;',
		220,18,90,250,700,875,1050,3 ];
        propertyArray[24] = ['Mass ave.','red',
		'left:180px;top:5px;',
		'left:112px;top:1px;height:25px;width:24px;',
		240,20,100,300,750,925,1100,3 ];
        propertyArray[25] = ['Orangeline','white',
		'left:60px;top:5px;border-style:solid;border-width:1px;',
		'left:137px;top:1px;height:34px;width:26px;',
		200,,,,,,, ];
        propertyArray[26] = ['Washington st.','yellow',
		'left:200px;top:15px;',
		'left:164px;top:1px;height:25px;width:24px;',
		260,22,110,330,800,975,1150,3 ];
        propertyArray[27] = ['Harvard st.','yellow',
		'left:200px;top:10px;',
		'left:189px;top:1px;height:25px;width:24px;',
		260,22,110,330,800,975,1150,3 ];
        propertyArray[28] = ['Phone Company','white',
		'left:80px;top:10px;border-style:solid;border-width:1px;',
		'left:214px;top:1px;height:34px;width:25px;',
		150,,,,,,, ];
        propertyArray[29] = ['Beacon st.','yellow',
		'left:200px;top:5px;',
		'left:240px;top:1px;height:25px;width:24px;',
		280,22,120,360,850,1025,1200,3 ];
        propertyArray[30] = ['Go to Prison','white',
		'',
		'left:270px;top:3px;height:25px;width:24px;',
		0,,,,,,, ];
        propertyArray[31] = ['Memorial dr.','green',
		'left:220px;top:15px;',
		'left:274px;top:36px;height:24px;width:25px;',
		300,26,130,390,900,1100,1275,4 ];
        propertyArray[32] = ['Storrow dr.','green',
		'left:220px;top:10px;',
		'left:274px;top:61px;height:24px;width:25px;',
		300,26,130,390,900,1100,1275,4 ];
        propertyArray[33] = ['Social Circle','white',
		'',
		'left:274px;top:87px;height:24px;width:25px;',
		0,,,,,,, ];
        propertyArray[34] = ['Comm ave.','green',
		'left:220px;top:5px;',
		'left:274px;top:113px;height:24px;width:25px;',
		320,28,150,450,1000,1200,1400,4 ];
        propertyArray[35] = ['Silverline','white',
		'left:60px;top:0px;border-style:solid;border-width:1px;',
		'left:265px;top:138px;height:24px;width:34px;',
		200,,,,,,, ];
        propertyArray[36] = ['Luck of the Draw','white',
		'',
		'left:274px;top:163px;height:24px;width:25px;',
		0,,,,,,, ]
        propertyArray[37] = ['Boylston','blue',
		'left:240px;top:15px;',
		'left:274px;top:189px;height:24px;width:25px;',
		350,35,175,500,1100,1300,1500,4 ];
        propertyArray[38] = ['Charity Drive','white',
		'',
		'left:274px;top:215px;height:24px;width:25px;',
		0,,,,,,, ];
        propertyArray[39] = ['Newbury st.','blue',
		'left:240px;top:10px;',
		'left:274px;top:240px;height:24px;width:25px;',
		400,50,200,600,1400,1700,2000,4 ];


/*
        propertyArray[0] = ['Go','white',
        propertyArray[1] = ['Mediteranean ave.','#550033',
        propertyArray[2] = ['Community Chest','white',
        propertyArray[3] = ['Baltic ave.','#550033'
        propertyArray[4] = ['Income Tax<br>pay 10% or $200','white',
        propertyArray[5] = ['Reading Railroad','white',
        propertyArray[6] = ['Oriental ave.','#6C8CAF',
        propertyArray[7] = ['Chance','white',
        propertyArray[8] = ['Vermont ave.','#6C8CAF',
        propertyArray[9] = ['Connecticut ave.','#6C8CAF',
        propertyArray[10] = ['Jail','white',
        propertyArray[11] = ['St. Charles Pl.','maroon',
        propertyArray[12] = ['Electric Company','white',
        propertyArray[13] = ['States ave.','maroon',
        propertyArray[14] = ['Virginia ave.','maroon',
        propertyArray[15] = ['Pennsylvania Railroad','white',
        propertyArray[16] = ['St. James Pl.','orange',
        propertyArray[17] = ['Community Chest','white',
        propertyArray[18] = ['Tennesee ave.','orange',
        propertyArray[19] = ['New York ave.','orange',
        propertyArray[20] = ['Free Parking','white',
        propertyArray[21] = ['Kentucky ave.','red',
        propertyArray[22] = ['Chance','white',
        propertyArray[23] = ['Indiana ave.','red',
        propertyArray[24] = ['Illinois ave.','red',
        propertyArray[25] = ['B & O Railroad','white',
        propertyArray[26] = ['Atlantic ave.','yellow',
        propertyArray[27] = ['Ventnor ave.','yellow',
        propertyArray[28] = ['Water Works','white',
        propertyArray[29] = ['Marvin Gardens','yellow',
        propertyArray[30] = ['Go To Jail','white',
        propertyArray[31] = ['Pacific ave.','green',
        propertyArray[32] = ['North Carolina ave.','green',
        propertyArray[33] = ['Community Chest','white',
        propertyArray[34] = ['Pennsylvania ave.','green',
        propertyArray[35] = ['Short Line','white',
        propertyArray[36] = ['Chance','white',
        propertyArray[37] = ['Park pl.','blue',
        propertyArray[38] = ['Luxury Tax<br>pay $75','white',
        propertyArray[39] = ['Board Walk','blue',
*/
} catch(x) { if ( debug ) Mojo.Log.error('Exception in creating property array: ' + x); }
}

StageAssistant.prototype.setChanceGlobal = function() {
        chanceCards = [
                'Get Out of Jail Free',
                'Take a Walk on ' + propertyArray[39][propertyName] + '<br>Advanced Token to ' + propertyArray[39][propertyName],
                'Advance to ' + propertyArray[24][propertyName] + '<br>If you pass "Go" collect $200',
                'Your Building and Loan Matures<br>Receive $150',
                'You Have Been Elected Chairman of the Board<br>Pay each player $50',
                'You Are Assessed for Street Repairs<br>$40 per house<br>$115 per hotel',
                'Advance to ' + propertyArray[11][propertyName] + '<br>if you pass "Go" collect $200',
                'Advance to ' + propertyArray[0][propertyName],
                'Pay School Tax of $150',
                'Take a Ride on the ' + propertyArray[5][propertyName] + '<br>If you pass "Go" collect $200',
                'Go to Jail<br>Move directly to jail<br>Do not pass "Go"<br>Do not collect $200',
                'Pay Poor Tax of $12',
                'Your Xmas Fund Matures<br>Collect $100',
                'Pay Parking Fine $15',
                'Make General Repairs on All of Your Houses<br>for each house pay $25<br>for each hotel pay $100',
                'Bank Pays You Dividend of $50'
        ];
}
StageAssistant.prototype.setCommunityChestGlobal = function() {
        communitychestCards = [
                'Get Out of Jail Free',
                'A collection has been taken up and everyone must donate 10% of his holdings to you (cash)',
                'We\'re Off the Gold Standard<br>Collect $50',
                'Pay Hospital $100',
                'Receive for Services $25',
                'Doctor\'s Fee Pay $50',
                'Go to Jail<br>Do not pass "Go"<br>Do not collect $200',
                'Bank Error in Your Favor<br>Collect $200',
                'Life Insurance Matures<br>Collect $100',
                'From Sale of Stock You Get $45',
                'Income Tax Refund<br>Collect $20',
                'You have won second prize in a beauty contest<br>collect $11',
                'Advance to ' + propertyArray[0][propertyName],
                'Advance token to the nearest railroad and pay owner twice the rental to which he is otherwise entitled.<br>If railroad is unowned, you may buy it from the bank',
                'You Inherit $100',
                'Grand Opera Opening<br>Collect $50 from every player for opening night seats'
        ];
}

monopolyHasHouses = function(testproperty) {
try {
  if ( testproperty == null ) return 0;

  var monopoly = getMonopoly(testproperty);
  if ( ! monopoly.length ) return 0;
  for ( var i=0; i<monopoly.length; i++ )
    if ( propertyOwner[monopoly[i]].ownedHouses > 0 ) return 1;
  return 0;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in monopoly has houses: ' + x); }
}

sameMonopoly = function(propertyOne, propertyTwo) {
  var monopoly = getMonopoly(propertyOne);
  if ( monopoly.length <= 0 ) return 0;
  for ( var n=0; n<monopoly.length; n++ ) {
    if ( propertyTwo == monopoly[n] ) return 1;
  }
  return 0;
}

isMonopoly = function(testproperty, user) {
try {
  if ( testproperty == undefined ) return 0;
  if ( user == undefined ) user = propertyOwner[testproperty].owner;

  var monopoly = getMonopoly(testproperty);
  if ( ! monopoly.length ) return 0;
  for ( var i=0; i<monopoly.length; i++ )
    if ( propertyOwner[monopoly[i]].owner != user ) return 0;
  return 1;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in is monopoly: ' + x); }
}

getMonopoly = function(testproperty) {
try {
  if ( testproperty == 1 || testproperty == 3 ) {
    return [ 1, 3 ]; }
  else if ( testproperty == 6 || testproperty == 8 || testproperty == 9 ) {
    return [ 6, 8, 9 ]; }
  else if ( testproperty == 11 || testproperty == 13 || testproperty == 14 ) {
    return [ 11, 13, 14 ]; }
  else if ( testproperty == 16 || testproperty == 18 || testproperty == 19 ) {
    return [ 16, 18, 19 ]; }
  else if ( testproperty == 21 || testproperty == 23 || testproperty == 24 ) {
    return [ 21, 23, 24 ]; }
  else if ( testproperty == 26 || testproperty == 27 || testproperty == 29 ) {
    return [ 26, 27, 29 ]; }
  else if ( testproperty == 31 || testproperty == 32 || testproperty == 34 ) {
    return [ 31, 32, 34 ]; }
  else if ( testproperty == 37 || testproperty == 39 ) {
    return [ 37, 39 ]; }
  return [];
} catch(x) { if ( debug ) Mojo.Log.error('Exception in get monopoly: ' + x); }
}

buyHouse = function(property) {
try {
  var player = propertyOwner[property].owner;
  //debugMessage("buyHouse");

  if ( isRR(property) ) return 1;
  if ( isUtil(property) )return 1;
  if ( ! isMonopoly(property, player) ) return 1;

  var monopoly = getMonopoly(property);
		// if not complex debts then unmortgage any mortgaged properties
  if ( prefs.complexDebts != 'true' ) {
    //if ( playerDebt(player) > prefs.maxDebt ) return 1;
    //debugMessage("let's unmortgage stuff first...");
    for ( var i=(monopoly.length - 1); i>=0; i-- ) {
      if ( propertyOwner[ monopoly[i] ].propertyMortgaged )
        unmortgageProperty( monopoly[i] );
    }
  }
                // make sure that there aren't any properties with fewer houses than this one.
  for ( var i=(monopoly.length - 1); i>=0; i-- ) {
    if ( propertyOwner[ monopoly[i] ].ownedHouses < propertyOwner[property].ownedHouses ) {
      property = monopoly[i];
      break;
    }
  }

  if ( propertyOwner[property].ownedHouses >= 5 ) return 1;

  var houseprice = Math.round(propertyArray[property][housePrice] * prefs.housePriceMultiplier);

  if ( isComputer(player) && prefs.complexDebts == 'true' ) {
    if ( playerArray[player].money < houseprice * prefs.moneyDown ) {
      return 1;
    }
    else if ( playerArray[player].money < houseprice ) {
      borrowMoney(player, houseprice );
    }
  }

  if ( playerArray[player].money >= houseprice ) {
    playerArray[player].money -= houseprice;
    propertyOwner[property].ownedHouses++;
    return 0;
  }

  return 1;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in make loan payment: ' + x); }
}

getLoanPayment = function(player) {
try{
  var payment = 0;

		// loan payment is settled regardless.  settle debts will handle it if we go negative
  playerArray[player].debt += Math.round( playerArray[player].debt * prefs.interestRate );
  var properties = listOwnedProperties(player);
  for ( var i=0; i< properties.length; i++ ) {
    var property = properties[i];
    if ( propertyOwner[property].debt ) {
      propertyOwner[property].debt += Math.round( propertyOwner[property].debt * prefs.interestRate );

		// if our final payment is larger or equal to our debt then pay it off.
      if ( propertyArray[property][price] * prefs.minimumPayments >= propertyOwner[property].debt ) {
        payment += propertyOwner[property].debt;
        propertyOwner[property].debt = 0;
        propertyOwner[property].propertyMortgaged = 0;
      }
      else {
        payment += Math.round( propertyArray[property][price] * prefs.minimumPayments );
        propertyOwner[property].debt -= Math.round( propertyArray[property][price] * prefs.minimumPayments );
      }
    }
  }

  if ( playerArray[player].debt * prefs.minimumPayments >= playerArray[player].debt ) {
    payment += playerArray[player].debt;
    playerArray[player].debt = 0;
  }
  else {
    payment += Math.round(playerArray[player].debt * prefs.minimumPayments);
    playerArray[player].debt -= Math.round( playerArray[player].debt * prefs.minimumPayments );
  }

  /*
  if ( payment && playerArray[player].money >= payment ) {
    playerArray[player].money -= payment;
    bankMoney += payment;
  }
  else {
    playerArray[player].stillowe += payment;
    playerArray[player].stilloweto = -2;
  }
  */

  return payment;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in make loan payment: ' + x); }
}

borrowMoney = function(player, money) {
try{
  if ( playerArray[player].money < ( money * prefs.moneyDown ) ) return 0;
		// subtract money down from player's money
  playerArray[player].money -= Math.round( money * prefs.moneyDown );
		// add borrowed ammount to player's debt
  playerArray[player].debt += Math.round( money * ( 1 - prefs.moneyDown ) );
		// calculate new minimum payment for player
  //playerArray[player].debtpayment += Math.round( money * prefs.minimumPayments );
  return 1;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in borrow money: ' + x); }
}

debugMessage = function(message) {
  if ( ! debug ) return 0;
  Mojo.Log.error(message);
}

sellHouse = function(property) {
  var player = propertyOwner[property].owner;
  var monopoly = getMonopoly(property);
  for ( var i=(monopoly.length - 1); i>=0; i-- ) {
    if ( propertyOwner[ monopoly[i] ].ownedHouses > propertyOwner[property].ownedHouses ) {
      property = monopoly[i];
      break;
    }
  }
  if ( propertyOwner[property].ownedHouses <= 0 ) return 1;
  if ( prefs.complexDebts == 'true' )
    playerArray[player].money += Math.round(propertyArray[property][housePrice] * prefs.housePriceMultiplier);
  else
    playerArray[player].money += Math.round( ( propertyArray[property][housePrice] * prefs.housePriceMultiplier ) * prefs.houseBuyBackRate );
  propertyOwner[property].ownedHouses--;
}

sellHouses = function(property, money) {
  if ( money == null ) money = 0;
  var monopoly = getMonopoly(property);
  for ( var i=0; i<monopoly.length; i++ ) {
    while ( propertyOwner[ monopoly[i] ].ownedHouses )
      sellHouse( monopoly[i] );
  }
}

playerDebt = function(player) {
  var debt = playerArray[player].debt;
  var properties = listOwnedProperties(player);
  for ( var i=0; i<properties.length; i++ )
    debt += propertyOwner[properties[i]].debt;
  return debt;
}

mortgageProperty = function(property, player) {
try {
  debugMessage("mortgaging " + propertyArray[property][propertyName] );

  if ( propertyOwner[property].owner != null && propertyOwner[property].owner != player ) {
    debugMessage("curplayer tried to mortgage " + propertyArray[property][propertyName] + " but is isn't theirs!");
    return 1;
  }

  if ( propertyOwner[property].propertyMortgaged )
    return 1;

  if ( prefs.complexDebts == 'true' ) {
    //if ( playerDebt(player) > prefs.maxDebt ) return 1;
    //debugMessage("player is over maxdebt");

    //sellHouses(property);
    var borrowmoney = Math.round(propertyArray[property][price] * ( 1 - prefs.moneyDown ));
    propertyOwner[property].debt = borrowmoney;
    playerArray[player].money += borrowmoney
    bankMoney -= borrowmoney
  }
  else {
    sellHouses(property);
    playerArray[player].money += Math.round( propertyArray[property][price] * prefs.mortgageValue );
    bankMoney -= Math.round( propertyArray[property][price] * prefs.mortgageValue );
  }
  propertyOwner[property].propertyMortgaged = 1;
} catch(x) { if ( debug ) Mojo.Log.error('Exception: ' + x); }
}

unmortgageProperty = function(property, player) {
try {
  //debugMessage("unmortgageing property");
  if ( player == null )
    player = propertyOwner[property].owner;

  if ( ! propertyOwner[property].propertyMortgaged ) return 1;

  if ( prefs.complexDebts == 'true' ) {
    if ( playerArray[player].money < propertyOwner[property].debt ) return 1;
    playerArray[player].money -= propertyOwner[property].debt;
    bankMoney += propertyOwner[property].debt;
    propertyOwner[property].debt = 0;
    propertyOwner[property].propertyMortgaged = 0;
    return 0;
  }
  else {
    var unmortgageVal = Math.round( ( propertyArray[property][price] * prefs.mortgageValue ) * ( 1 + prefs.mortgageRate ) );
    if ( playerArray[player].money < unmortgageVal ) return 1;
    playerArray[player].money -= unmortgageVal
    propertyOwner[property].propertyMortgaged = 0;
    bankMoney += unmortgageVal;
    return 0;
  }

  return 1;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in unmortgage property: ' + x); }
}

		// all properties owned by a given player
listOwnedProperties = function(player) {
  var properties = [];
  if ( player == null ) return properties;
  if ( player < 0 ) return properties;
  for ( var i in propertyOwner ) {
    if ( propertyOwner[i].owner == player ) properties.push(i);
  }
  return properties;
}

propertyTradeValue = function(property, player) {
try {
  if ( property == null ) return 0;
  var owner = propertyOwner[property].owner;
  var value = 0;


  if ( prefs.complexDebts != 'true' ) {
    if ( propertyOwner[property].ownedHouses ) {
      value += Math.round( ( propertyArray[property][housePrice] * prefs.housePriceMultiplier ) * prefs.houseBuyBackRate);
    }
  }

  var count = countOwnedPropsInMonopoly(property, player);
  var monopoly = getMonopoly(property);

                // railroads and utilities
  if ( isRR(property) || isUtil(property) ) {
    value += propertyArray[property][price] * 2;
  }
                // breaking up an existing monopoly +10x
  else if ( isMonopoly(property, owner) ) {
    value += propertyArray[property][price] * 8;
  }

                // this would create a monopoly
  else if ( count >= ( monopoly.length - 1 ) ) {
    value += propertyArray[property][price] * 8;
  }
		// you have at least one property
  else if ( count >= 1 ) {
    value += propertyArray[property][price] * 4;
  }
  else {
    value += propertyArray[property][price] * 2;
  }

		// it's mortgaged
  if ( propertyOwner[property].propertyMortgaged )
    if ( prefs.complexDebts == 'true' )
      value -= propertyOwner[property].debt;
    else
      value -= Math.round( propertyArray[property][price] * prefs.mortgageValue );

		// if player owes money then maybe this property is worth more to them than usual.
  if ( player != curPlayer ) {
    if ( playerArray[curPlayer].stillowe > playerArray[curPlayer].money ) {
      value = Math.round(value / 2);
      //debugMessage('value of ' + propertyArray[property][propertyName] + " is halved because " + playerArray[player].playerName + ' is in debt');
    } 
  }

  //debugMessage("trade value for " + propertyArray[property][propertyName] + ": " + value);
  return value;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in property trade value: ' + x); }
}

		// given a property count the properties owned in that monopoly
countOwnedPropsInMonopoly = function(property, player) {
  if ( player == undefined ) player = propertyOwner[property].owner;

  var count = 0;
  var monopoly = getMonopoly(property);
  for ( var i=0; i<monopoly.length; i++ ) {
    if ( propertyOwner[ monopoly[i] ].owner != null && propertyOwner[ monopoly[i] ].owner == player )
      count++;
  }
  return count;
}

getPropertyAssets = function(player) {
try {
  var total = 0;
  var properties = listOwnedProperties(player);
  for ( var i=0; i<properties.length; i++ ) {
    var property = properties[i];
    if ( propertyOwner[property].propertyMortgaged ) continue;
    if ( prefs.complexDebts == 'true' )
      total += Math.round( propertyArray[property][price] * ( 1 - prefs.moneyDown ) );
    else
      total += Math.round( propertyArray[property][price] * prefs.mortgageValue );
  } 
  return total;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in property value: ' + x); }
}

getHouseAssets = function(player) {
try {
  var total = 0;
  var properties = listOwnedProperties(player);
  for ( var i=0; i<properties.length; i++ ) {
    var property = properties[i];
    if ( propertyOwner[property].ownedHouses ) {
      if ( prefs.complexDebts == 'true' )
        total += Math.round(propertyArray[property][housePrice] * prefs.housePriceMultiplier);
      else
        total += Math.round( ( propertyArray[property][housePrice] * prefs.housePriceMultiplier ) * prefs.houseBuyBackRate );
    }
  } 
  return total;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in house value: ' + x); }
}

getMortgageableAssets = function(player) {
try {
  var total = 0;
  var properties = listOwnedProperties(player);
  for ( var i=0; i<properties.length; i++ ) {
    var property = properties[i];
    if ( propertyOwner[property].ownedHouses ) continue;
    if ( isMonopoly(property, player) ) continue;
    if ( propertyOwner[property].propertyMortgaged ) continue;
    if ( prefs.complexDebts == 'true' )
      total += Math.round( propertyArray[property][price] * ( 1 - prefs.moneyDown) );
    else
      total += Math.round( propertyArray[property][price] * prefs.mortgageValue );
  } 
  return total;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in property value: ' + x); }
}

StageAssistant.prototype.handleCommand = function(event) {

    //  Find the current scene
    var currentScene = Mojo.Controller.stageController.activeScene();

    if(event.type == Mojo.Event.command) {
	switch(event.command) {

	    case 'do-about':
	        currentScene.showAlertDialog({
	        onChoose: function(value) {},
	            title: $L("Preopoly - v0.0.11"),
		    message: $L("Copyright (C) 2009 Lawren Quigley-Jones\nquigley-jones.com"),
		    choices:[
	                {label:$L("OK"), value:""}
                    ]
                });
                break;

             case 'do-prefs':
                 Mojo.Controller.stageController.pushScene("preferences", this);
                 break;

             case 'do-assets':
		 if ( ! prefs.bankMode == 'true' && ! isComputer(curPlayer) )
                   Mojo.Controller.stageController.pushScene("props", this);
                 break;

             case 'do-help':
                 Mojo.Controller.stageController.pushScene("help", this);
                 break;
	 }
    }
};

autoSellHouses = function(player, money) {
try {
  if ( playerArray[player].money >= money ) return 1;
  var total = getHouseAssets(player);
  if ( total < money ) return 0;
  return sellHousesAndMortgage(player, money);
} catch(x) { debugMessage("Exception in auto sell houses: " + x); }
}

sellHousesAndMortgage = function(player, money) {
  var properties = listOwnedProperties(player);
  if ( properties.length <= 0 ) return 0;

		// for each owned properties
  for ( var i=(properties.length - 1); i>= 0; i-- ) {
    property = properties[i];

    if ( playerArray[player].money >= money ) return 1;

    if ( ! isMonopoly(property, player) ) continue;

    sellHouses(property, money)

		// sell all houses
    //while ( propertyOwner[property].ownedHouses ) {
    //  if ( playerArray[player].money >= money ) return 1;
    //  sellHouse(property);
    //}
    if ( playerArray[player].money >= money ) return 1;
    
    jproperties = getMonopoly(property);
    for ( var j=(jproperties.length - 1); j>= 0; j-- ) {
      jproperty = jproperties[j];

      if ( playerArray[player].money >= money ) return 1;
      if ( ! propertyOwner[jproperty].propertyMortgaged )
        mortgageProperty(jproperty, player);
    }
  }
}

autoMortgage = function(player, money) {
try {
  debugMessage("raising $" + money);
  if ( playerArray[player].money >= money ) return 1;
  if ( money > getMortgageableAssets(player) + playerArray[player].money ) return 0;
  return mortgageAll(player, money);
} catch(x) { debugMessage("Exception in save prefs cookie: " + x); }
}

mortgageAll = function(player, money) {
  var properties = listOwnedProperties(player);
  if ( properties.length <= 0 ) return 0;
  for ( var i=(properties.length - 1); i>= 0; i-- ) {
    var property = properties[i];
    //debugMessage("property: " + propertyArray[property][propertyName]);
    if ( playerArray[player].money >= money ) return 1;
    if ( isMonopoly(property, player) ) continue;
    if ( propertyOwner[property].ownedHouses > 0 ) continue;
    if ( propertyOwner[property].propertyMortgaged ) continue;
    mortgageProperty(property, player);
  }
  return 0;
}

savePrefsCookie = function() {
  var prefsCookie = new Mojo.Model.Cookie("PreferencesCookie");
  prefsCookie.put(prefs);
}

loadPrefsCookie = function() {
  var prefsCookie = new Mojo.Model.Cookie("PreferencesCookie");
  prefs = prefsCookie.get();
}

performTrade = function(offerHash, requestHash) {
try {
  if ( offerHash.money != undefined )
    if ( offerHash.money > playerArray[offerHash.player].money )
      return 0;

  if ( requestHash.money != undefined )
    if ( requestHash.money > playerArray[requestHash.player].money )
      return 0;

  if ( offerHash.money != undefined ) {
    playerArray[offerHash.player].money -= offerHash.money;
    playerArray[requestHash.player].money += offerHash.money;
  }

  if ( requestHash.money != undefined ) {
    playerArray[offerHash.player].money += requestHash.money;
    playerArray[requestHash.player].money -= requestHash.money;
  }

  if ( offerHash.properties != undefined ) {
    for ( var i=0; i<offerHash.properties.length; i++ ) {
      property = offerHash.properties[i];
      while ( propertyOwner[property].ownedHouses > 0 )
        sellHouses(property);
      propertyOwner[property].owner = requestHash.player;
    }
  }

  if ( requestHash.properties != undefined ) {
    for ( var i=0; i<requestHash.properties.length; i++ ) {
      property = requestHash.properties[i];
      while ( propertyOwner[property].ownedHouses > 0 )
        sellHouses(property);
      propertyOwner[property].owner = offerHash.player;
    }
  }
  return 1;
} catch(x) { if ( debug ) Mojo.Log.error('Exception in perform trade: ' + x); }
}

tradeText = function(offerHash, requestHash) {
  var offerText = "";
  offerText += playerArray[offerHash.player].playerName + "'s ";
  if ( offerHash.properties.length ) {
    offerText += propertyArray[offerHash.properties[0]][propertyName];
    if ( offerHash.properties.length > 1 ) {
      for ( i=1; i<offerHash.properties.length; i++ )
        offerText += " and " + propertyArray[offerHash.properties[i]][propertyName];
    }
  }
  if ( offerHash.money ) offerText += " plus $" + offerHash.money;
  offerText += " for ";
  offerText += playerArray[requestHash.player].playerName + "'s ";
  if ( requestHash.properties.length ) {
    offerText += propertyArray[requestHash.properties[0]][propertyName];
    if ( requestHash.properties.length > 1 ) {
      for ( i=1; i<requestHash.properties.length; i++ )
        offerText += " and " + propertyArray[requestHash.properties[i]][propertyName];
    }
  }
  if ( requestHash.money ) offerText += " plus $" + requestHash.money;
  return offerText;
}

shuffle = function(myA) {
  for ( var tmp, j, i = myA.length; i; )
  {
    j = Math.floor( Math.random() * i );
    tmp = myA[--i];
    myA[i] = myA[j];
    myA[j] = tmp;
  }
  return myA;
}

shuffleCards = function(len) {
                // create an array of shuffled numbers
  var myA = [];
  for (i = 0; i < len; i++) {
    myA[i] = i;
  }
  //if ( debug ) Mojo.Log.error("shuffled cards " + shuffle.join(" "));
  return shuffle(myA);
}

isComputer = function(player) {
  if ( prefs.bankMode == 'true' )
    return 1;
  else if ( playerArray[player].playerType == "human" )
    return 0;
  else if ( playerArray[player].playerType == "computer" )
    return 1;
  else
    return -1;
}

isRR = function(property) {
  if ( property == 5 || property == 15 || property == 25 || property == 35 )
    return 1;
  else
    return 0;
}

isUtil = function(property) {
  if ( property == 12 || property == 28 )
    return 1;
  else
    return 0;
}

popup = function(thisObj, text) {
  thisObj.controller.showAlertDialog({
    onChoose: function(value) {},
    title: $L( text ),
    choices:[ {label:$L("OK"), value:""} ]
  });
}
